<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8 ">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>websocket client</title>
</head>
<body>
    <form onSubmit="return false;">
        <input type="text" name="message" value="" />
        <br/> <br/>
        <input type="button" name="btn" value="发送ws请求消息" onclick="send(this.form.message.value)">
        <hr color="red">
        <h2>客户端接收到服务端返回的应答消息</h2>
        <textarea name="responseText" id="textarea" cols="80" rows="50"></textarea>
    </form>
    <script type="text/javascript">
        var socket ;
    
        if(!window.WebSocket){
            window.WebSocket = window.MozWebSocket;
        }
        if(window.WebSocket) {
            socket = new WebSocket("ws://localhost:8888/websocket");
            socket.onmessage = function (event) {
                var ta  = document.getElementById("textarea");

                ta.value += event.data +"\r\n"
                
            }
            socket.onopen = function(event){
                var ta  = document.getElementById("textarea");
                ta.value = "您当前浏览器支持ws,请继续操作。。。\r\n"
            }

            socket.onclose = function(event){
                var ta  = document.getElementById("textarea");
        
                ta.value = ""
                ta.value = "ws链接已关闭\r\n"
            }
            
        }else{
            alert("您的浏览器不支持ws\r\n")
        }


        function send(msg){
            if(!window.WebSocket){
                alert("您的浏览器不支持ws\r\n")
            }
            if (socket.readyState === WebSocket.OPEN) {
                socket.send(msg)
            }else{
                alert("ws连接没有建立成功\r\n")
            }
        }
    </script>
</body>
</html>